package com.luo.springboot_luo.controller;

import com.luo.springboot_luo.pojo.Results;
import com.luo.springboot_luo.pojo.dto.UserDTO;
import com.luo.springboot_luo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController // 允许接口方法可以返回JSON数据
@RequestMapping("/users") // 设置请求路径 localhost:8080/users/**
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    //添加
    @PostMapping  // 添加用户 url:localhost:8080/users method:POST
    public Results add(@Validated @RequestBody UserDTO user) {
        return Results.success(userService.addUser(user));
    }


    //查询
    @GetMapping("/{userId}") // 查询用户列表 url:localhost:8080/users/1 method:GET
    public Results getUser(@PathVariable Integer userId) {
        return Results.success(userService.getUser(userId));
    }

    //修改
    @PutMapping // 更新用户信息 url:localhost:8080/users method:PUT
    public Results update(@Validated @RequestBody UserDTO user) {
        // 这里可以添加更新用户的逻辑
        return Results.success(userService.setUser(user));
    }

    //删除
    @DeleteMapping("/{userId}") // 删除用户 url:localhost:8080/users/1 method:DELETE
    public Results delete(@PathVariable Integer userId) {
        userService.deleteUser(userId);
        return Results.success();
    }
}
